// 封装get请求	

// 基础url this.api.baseUrl
// export const baseUrl = "http://bodexiong.vip:2101"
// export const baseUrl = "http://127.0.0.1:8000"
// export const baseUrl = "https://bodexiong.vip"
export const baseUrl = "https://regist.dzeducation.com"


export function myTest(a){
	console.log('~~~~~~~~~~~~~ myTest ~~~~~~~~~~~~~~~~~~~~~~~');
	console.log(a);
	console.log('~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
}


function isMobile() {
	let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
	return flag?true:false;
}


export function isArrayFn (o) {
	if (o == undefined)
	return false
	
	return Object.prototype.toString.call(o) === '[object Array]';
}


export function previewImages(urls, index) {
			// 预览图片
			// - 用法: previewImages(url)或者previewImages(urls, index)
			if (index == undefined) 	index = 0;
			if (!isArrayFn(urls)) urls = [urls];

			uni.previewImage({
				urls: urls,
				current: index,
				indicator: 'default',
				longPressActions: {
					itemList: ['发送给朋友', '保存图片', '收藏'],
					success: function(data) {
						console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
					},
					fail: function(err) {
						console.log(err.errMsg);
					}
				}
		  	});
}


function myEncodeListFunction(key, value){
		// key为list的键名, value为list的值, 如{'name': ['aa', 'bb', 'cc']}
		// if (value == undefined)	console.log('-------- value不能为空!')
		if (isArrayFn(value) == false)	console.log('****** value必须为list! ---from myEncodeListFunction')
		
		var myArrayStr = ""
		for (var i in value){
			var a = value[i];
			var aStr = encodeURIComponent(a);
			myArrayStr += '&' + key + '=' + aStr;
		}
		return myArrayStr
	}


export function getValuesFromPrePage(key_ls, set_dc){
	// --- 接收从上个页面传过来的值
	// key_ls: 从上一个页面中传过来的key
	// set_dc: 将这个dict的key设置为对应变量
	
	/* 调用页面获取图片URL方法 */
	let pages = getCurrentPages();
	let currPage = pages[pages.length-1];
	let that = this;
	
	for(var i in key_ls){
		var key_i = key_ls[i];
		var tmp_key_i = '_' + key_i;
		var value_i = currPage.data[tmp_key_i];
		
		// console.log('for --- ', tmp_key_i, '~~', value_i);
		
		if(typeof(value_i) != undefined && value_i != null){
			console.log('成功获取临时变量tmp_key_i: ', tmp_key_i, ' --- ', value_i);
			set_dc[key_i] = value_i;
			
			currPage.data[tmp_key_i] = null;		// 只获取一次
		};
	}
}


export function getMyUrlParams(options){
	var strData = '';
	let data_dc = options.data;
	for(var k in data_dc){
		var v = data_dc[k];
		if (isArrayFn(v)){
			strData += myEncodeListFunction(k, v);
		}
		else{
			v = encodeURIComponent(v);
			strData += '&' + k + '=' + v;
		}
	}
	
	var myUrl = baseUrl + options.url + '?' + strData;
	return myUrl
}


export const myGetFunction = (options)=>{
	var strData = '';
	let data_dc = options.data;
	for(var k in data_dc){
		var v = data_dc[k];
		if (isArrayFn(v)){
			strData += myEncodeListFunction(k, v);
		}
		else{
			v = encodeURIComponent(v);
			strData += '&' + k + '=' + v;
		}
	}
	
	var myUrl = baseUrl + options.url + '?' + strData;
	return new Promise((resolve,reject)=>{
		uni.request({
			method: 'GET',
			url: myUrl,
			success(res) {
				if (res.statusCode != 200){
					uni.showToast({
						title: '请求失败! 状态码: ' + String(res.statusCode),
						icon: 'none',
					})
					console.log('Error myGetFunction, res: ', res);
				}
				resolve(res)
			},
			fail(err) {
				
				uni.showToast({
					title: '获取数据失败',
					icon: 'none',
				})
				reject(err)
			}
		})
	})
}


export const myRequest = (options)=>{
	return new Promise((resolve,reject)=>{
		// 可以用not_add_base_url来选择是否增加baseUrl前缀(默认加baseUrl)
		var not_add_base_url = options.not_add_base_url;
		
		var myUrl = options.url;
		if (!not_add_base_url){
			myUrl = baseUrl + options.url;
		}
		uni.request({
			method: options.method,
			data: options.data,
			url: myUrl,
			success(res) {
				resolve(res)
			},
			fail(err) {
				uni.showToast({
					title: '获取数据失败',
					icon: 'none',
				})
				reject(err)
			}
		})
	})
}


export const myUploadFile = (options)=>{
	return new Promise((resolve,reject)=>{
		// 可以用not_add_base_url来选择是否增加baseUrl前缀(默认加baseUrl)
		var not_add_base_url = options.not_add_base_url;
		
		var myUrl = options.url;
		if (!not_add_base_url){
			myUrl = baseUrl + options.url;
		}
		if (!options.filePath){
			var msg = "图片地址为空!"
			console.log(msg)
			uni.showToast({
			    title: msg,
				icon: 'none',
			    duration: 1000
			});
			resolve(msg)
			// reject(msg)
		}
		
		// 这里用来区分是http文件还是本地待上传文件
		if (options.filePath) {
			if(options.filePath.indexOf("/api/") !== -1){
				var msg = "----------- 这是超链接文件, 已忽略!"
				console.log(msg)
				uni.showToast({
				    title: msg,
					icon: 'none',
				    duration: 1000
				});
				// reject(msg)
				resolve(msg)
			}
		}
		
		console.log('------ myUrl: ', myUrl);
		uni.uploadFile({
			url: myUrl,
			method: options.method,
			
			filePath: options.filePath,
			name: options.name,
			formData: options.formData,
			success(res) {
				resolve(res)
			},
			fail(err) {
				msg = options.tag + '上传失败!'
				uni.showToast({
					title: msg,
					icon: 'none',
				})
				console.log('*** err:', err)
				reject(err)
			}
		})
	})
}


export function is_contains(ss, s) {
	if(ss.indexOf(s) !== -1){
		return 1
	}
	else {
		return 0
	}
}


export function uploadFileFunction(options) {
	return new Promise(function (resolve, reject) {
		// 可以用not_add_base_url来选择是否增加baseUrl前缀(默认加baseUrl)
		var not_add_base_url = options.not_add_base_url;
		
		var myUrl = options.url;
		if (!not_add_base_url){
			myUrl = baseUrl + options.url;
		}
		if (!options.filePath){
			var msg = options.tag + "的地址为空!"
			console.log(msg)
			uni.showToast({
				title: msg,
				icon: 'none',
				duration: 1000
			});
			resolve(msg)
			return
		}
		
		// 这里用来区分是http文件还是本地待上传文件
		if (options.filePath) {
			if(options.filePath.indexOf("/api/") !== -1){
				var msg = options.tag + " 为超链接, 已忽略!"
				console.log(msg)
				resolve(msg)
				return
			}
		}
		
		console.log('------ 	~~~~~ myUrl: ', myUrl);
		console.log('------ 	~~~~~ filePath: ', options.filePath);
		uni.uploadFile({
			url: myUrl,
			method: options.method,
			
			filePath: options.filePath,
			name: options.name,
			formData: options.formData,
			success(res) {
				resolve(res)
			},
			fail(err) {
				msg = options.tag + '上传失败!'
				uni.showToast({
					title: msg,
					icon: 'none',
				})
				console.log('*** err:', err)
				reject(err)
			}
		})
	});
	
}


export const myFileUpload = (options)=>{
	return new Promise((resolve,reject)=>{
		uni.uploadFile({
			method: options.method,
			formData: options.formData,
			url: baseUrl + options.url,
			name: options.name,
			filePath: options.filePath,
			success(res) {
				resolve(res)
			},
			fail(err) {
				uni.showToast({
					title: options.name + '文件上传失败',
					icon: 'none',
				})
				reject(err)
			}
		})
	})
}


export function get_keyname_value(data, key_name){
	// 将json数据中的某个字段转化为list
	var n = data.length
	var values = []
	for(var i = 0; i < n; i++){
		var dc = {
			"k": i,
			"v": data[i][key_name]
		}
		values.push(data[i][key_name])
		// values.push(dc)
	}
	// console.log('_______ values: ' + values)
	return values
}


export function add_hostname_before_keyname(data, keyname, new_keyname=''){
	if (new_keyname == ''){
		new_keyname = 'host_' + keyname
	}
	
	for(var i = 0; i < data.length; i++){
		 data[i][new_keyname] = baseUrl + data[i][keyname]
		 // console.log(data[i][new_keyname])
	}
					
	return data
}


	
export const get_v_by_kname = (options)=>{
	
	return new Promise( (resolve,reject)=>{
		
		get_keyname_value({
			data: options.data,
			key_name: options.key_name,
			success(res) {
				console.log('~~~ res ~~~')
				console.log(res)
				resolve(res)
			},
			fail(err) {
				uni.showToast({
					title: '获取数据失败'
				})
				reject(err)
			}
		})
	})
	

}



export function get_index_by_kv_in_dc_ls(dc_ls, key, value) {
	// 从dc_ls中获取指定key和value的index
	var index = 0;
	var flag = false;
	for(var i in dc_ls)
	{
		var dc = dc_ls[i];
		// console.log(dc);
		
		var v = dc[key];
		// console.log(i, v);
		
		if (v == value)
		{
			flag = true;
			break;
		}
		index += 1;
	}
	return flag? index : -1;
}


export var deepCopy = function(obj) {
  // 只拷贝对象
  if (typeof obj !== 'object') return;
  // 根据obj的类型判断是新建一个数组还是一个对象
  var newObj = obj instanceof Array ? [] : {};
  for (var key in obj) {
    // 遍历obj,并且判断是obj的属性才拷贝
    if (obj.hasOwnProperty(key)) {
      // 判断属性值的类型，如果是对象递归调用深拷贝
      newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
    }
  }
  return newObj;
}


export function conv_old_key_to_new_key_in_dc_ls(dc_ls, old_key, new_key) {
	  var n = dc_ls.length;
	  var new_dc_ls = deepCopy(dc_ls);
	  for(var i = 0; i < n; i++){
			new_dc_ls[i][new_key] = dc_ls[i][old_key]
			delete new_dc_ls[i][old_key]
	  }
	  return new_dc_ls
}